package com.he.DesignPatterns.Singleton;

/**
 * @description: TODO
 * @Author: HCL
 * @Date: 2024/8/23 15:25
 */
public class Client {

    public static void main(String[] args) {
//        Singleton singleton = new Singleton();    私有化构造不能使用new创建对象实例
        System.out.println("=================饿汉方法1-静态变量");
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);

        System.out.println("=================饿汉方法1-静态变量");
        SingletonTwo instance3 = SingletonTwo.getInstance();
        SingletonTwo instance4 = SingletonTwo.getInstance();
        System.out.println(instance3 == instance4);

        System.out.println("=================懒汉方法1-线程不安全");
        SingletonThree instance5 = SingletonThree.getInstance();
        SingletonThree instance6 = SingletonThree.getInstance();
        System.out.println(instance5 == instance6);
//        SingletonThree s1;
//        SingletonThree s2;
//        new Thread(()->{
//            s1 = SingletonThree.getInstance();
//        },"t1").start();
//
//        new Thread(()->{
//           s2 = SingletonThree.getInstance();
//        },"t2").start();

        //推荐使用以下方式
        System.out.println("=================懒汉方法2-双检锁线程安全，但锁消耗空间");
        SingleFour instance7 = SingleFour.getInstance();
        SingleFour instance8 = SingleFour.getInstance();
        System.out.println(instance7 == instance8);

        System.out.println("=================懒汉方法3-静态内部类线程安全");
        SingleFive instance9 = SingleFive.getInstance();
        SingleFive instance10 = SingleFive.getInstance();
        System.out.println(instance9 == instance10);

        System.out.println("=================饿汉方法3-枚举线程安全");
        SingletonEnum instance11 = SingletonEnum.INSTANCE;
        SingletonEnum instance12 = SingletonEnum.INSTANCE;
        System.out.println(instance11 == instance12);
    }
}
